package com.egene.zh.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.MySwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.egene.zh.R;
import com.egene.zh.ui.DividerItemDecoration;
import com.egene.zh.ui.EmptyLayout;
//import com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView;


public abstract class BaseRecycleViewFragment extends BaseTabFragment implements
        RecycleBaseAdapter.OnItemClickListener, RecycleBaseAdapter.OnItemLongClickListener {

    public static final String BUNDLE_KEY_CATALOG = "BUNDLE_KEY_CATALOG";
    private static final String TAG = "BaseRecycleViewFragment";

    protected static final int START_PAGE_INDEX = 1;
    protected static final int PAGE_SIZE = 10;


    protected MySwipeRefreshLayout mSwipeRefresh;
    protected RecyclerView mRecycleView;
    protected LinearLayoutManager mLayoutManager;
    protected RecycleBaseAdapter mAdapter;
    protected EmptyLayout mErrorLayout;
    protected int mStoreEmptyState = -1;
    protected String mStoreEmptyMessage;

    protected int mCurrentPage = START_PAGE_INDEX;
    protected boolean isNoMore = false;
//    protected int mCatalog = 1;

    protected View rootView;//缓存Fragment view

    //private AsyncTask<String, Void, ListEntity> mCacheTask;
//    private ParserTask mParserTask;

    private RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            int totalItemCount = mLayoutManager.getItemCount();
            if (lastVisibleItem >= totalItemCount - 4 && dy > 0) {
                if (mState == STATE_NONE && mAdapter != null
                        && mAdapter.getDataSize() > 0) {
                    loadMore();
                }
            }
        }
    };

    protected int getLayoutRes() {
        return R.layout.v2_fragment_swipe_refresh_recyclerview;
    }

//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        Bundle args = getArguments();
//        if (args != null) {
//            mCatalog = args.getInt(BUNDLE_KEY_CATALOG);
//        }
//    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(rootView==null){
            rootView = inflater.inflate(getLayoutRes(), container, false);
            initViews(rootView);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
//        View view = inflater.inflate(getLayoutRes(), container, false);
//        initViews(view);
//        return view;
    }

    protected void initViews(View view) {
        mErrorLayout = (EmptyLayout) view.findViewById(R.id.error_layout);
        mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mCurrentPage = START_PAGE_INDEX;
                mState = STATE_REFRESH;
                mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                requestData(true);
            }
        });

        mSwipeRefresh = (MySwipeRefreshLayout) view.findViewById(R.id.srl_refresh);
        mSwipeRefresh.setColorSchemeResources(R.color.main_green, R.color.main_gray, R.color.main_black, R.color.main_purple);
        mSwipeRefresh.setOnRefreshListener(new MySwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        mRecycleView = (RecyclerView) view.findViewById(R.id.recycleView);
        mRecycleView.setOnScrollListener(mScrollListener);

        if (isNeedListDivider()) {
            // use a linear layout manager
            mRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                    DividerItemDecoration.VERTICAL_LIST));
        }

        mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycleView.setLayoutManager(mLayoutManager);
        mRecycleView.setHasFixedSize(true);

        if (mAdapter != null) {
            mRecycleView.setAdapter(mAdapter);
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        } else {
            mAdapter = getListAdapter();
            mAdapter.setOnItemClickListener(this);
            mAdapter.setOnItemLongClickListener(this);
            mRecycleView.setAdapter(mAdapter);

            if (requestDataIfViewCreated()) {
                mCurrentPage = START_PAGE_INDEX;
                mState = STATE_REFRESH;
                mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                //requestData(requestDataFromNetWork());
//                new ReadCacheTask(this).execute();
            } else {
                mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            }
        }

        if (mStoreEmptyState != -1) {
            mErrorLayout.setErrorType(mStoreEmptyState);
        }
        if (!TextUtils.isEmpty(mStoreEmptyMessage)) {
            mErrorLayout.setErrorMessage(mStoreEmptyMessage);
        }
        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        sendRequestData();
    }

    @Override
    public void onDestroyView() {
        mStoreEmptyState = mErrorLayout.getErrorState();
        mStoreEmptyMessage = mErrorLayout.getMessage();
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onItemClick(View view) {
        onItemClick(view, mRecycleView.getChildPosition(view));
    }

    protected void onItemClick(View view, int position) {
    }

    @Override
    public boolean onItemLongClick(View view) {
        return onItemLongClick(view, mRecycleView.getChildPosition(view));
    }

    protected boolean onItemLongClick(View view, int position) {
        return false;
    }

    protected abstract RecycleBaseAdapter getListAdapter();

    protected boolean requestDataIfViewCreated() {
        return true;
    }

    protected String getCacheKeyPrefix() {
        return null;
    }

    protected void notifyDataSetChanged() {
        if (mAdapter != null)
            mAdapter.notifyDataSetChanged();
    }

    public void refresh() {
        mSwipeRefresh.setRefreshing(true);
        isNoMore = false;
        mCurrentPage = START_PAGE_INDEX;
        mState = STATE_REFRESH;
        requestData(true);
    }

    public void loadMore() {
        if(isNoMore){
            return;
        }
        if (mState == STATE_NONE) {
            mCurrentPage++;
            mState = STATE_LOADMORE;
            mAdapter.setState(
                    RecycleBaseAdapter.STATE_LOAD_MORE);
            requestData(false);
        }
    }

    protected void requestData(boolean refresh) {
        sendRequestData();
    }

    protected void sendRequestData() {

    }


    protected boolean isNeedListDivider() {
        return false;
    }

    protected void executeOnLoadFinish() {
        mSwipeRefresh.setRefreshing(false);
        mState = STATE_NONE;
    }

    protected void executeNoMore(){
        isNoMore = true;
        mSwipeRefresh.setRefreshing(false);
        mState = STATE_NONE;
        mAdapter.setState(RecycleBaseAdapter.STATE_NO_MORE);

    }
}
